package day15;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public
class ServerThead extends Thread {
    Socket client;

    public
    ServerThead(Socket client) {
        this.client = client;
    }

    //逻辑：先得到发送方和接收方的用户名 再根据用户名找到对应的socket 再进行通信
    //针对发送发进行读取 针对接收方进行写入
    //对方不在线时 是可以实现离线消息存储 可以以不发送消息
    public
    void run() {
        try (BufferedReader be = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
            String msg = be.readLine();
            if(msg == null) return;

            // 先处理注册消息
            if(msg.startsWith("register,")) {
                String username = msg.substring(9);
                Server.map.put(username, client);
                System.out.println(username + "上线了");
                return;
            }

            // 再处理聊天消息
            String[] parts = msg.split(",", 3);
            if(parts.length < 3) return;

            String username = parts[0];
            String toUsername = parts[1];
            String message = parts[2];

            while (true) {
                //读取发送方发送的消息
                msg = be.readLine();
//                if(msg.equals(username+"退出了聊天")){
//                    System.out.println(toUsername+"退出了聊天");
//                    return;
//                }
                if (msg == null||msg.equals("exit")) {  // 添加对null消息的判断
                    Server.map.remove(username);
                    return;
                }

                Socket toClient = Server.map.get(toUsername);
                if (toClient != null) {
                    OutputStream os = toClient.getOutputStream();
                    os.write((username + "说：" + msg + "\n").getBytes());
                } else {
                    OutputStream os = client.getOutputStream();
                    os.write((toUsername + "不在线，消息已保存\n").getBytes());
                }
            }


        } catch (Exception e) {
        }
    }
}
